<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/9/2
 * Time: 15:13
 */
namespace App\Services;

use App\Repositories\CreditCardHandleApplyRepository;
use App\Repositories\CreditCardHandleGrantRepository;
use App\Repositories\CreditCardHandleRepository;
use App\Repositories\UserLevelRepository;
use App\Repositories\UserRepository;
use App\Services\Xinyan\CertificationBankCardMsgAuth;
use Illuminate\Http\Request;

class CreditCardHandleApplyService extends CommonService
{
    protected $userRepository;
    protected $creditCardHandleApplyRepository;
    protected $creditCardHandleRepository;

    public function __construct(UserRepository $userRepository,
                                CreditCardHandleApplyRepository $creditCardHandleApplyRepository,
                                CreditCardHandleRepository $creditCardHandleRepository)
    {
        $this->userRepository = $userRepository;
        $this->creditCardHandleApplyRepository = $creditCardHandleApplyRepository;
        $this->creditCardHandleRepository = $creditCardHandleRepository;
    }

    /**
     * 获取办卡链接
     * @param $invitedUserId
     * @param $mobile
     * @param $code
     * @param $realname
     * @param $idCard
     * @param $creditCardHandleId
     * @return bool|\Illuminate\Http\JsonResponse
     */
    public function apply($invitedUserId, $mobile, $code, $realname, $idCard, $creditCardHandleId)
    {
        //验证身份证号码是否正确
        if (!validation_filter_id_card($idCard)) {
            return $this->responseJson(422, [], false, '身份证号码格式不正确', '身份证号码格式不正确');
        }
        $isCheck = $this->checkCode($mobile, $code, 'credit_card_handle');
        if (!$isCheck) {
            return $this->responseJson(10110);//短信验证码不正确
        }
        //验证需要办理的信用卡是否存在
        $creditCardHandleRepository = $this->creditCardHandleRepository->findByOpen($creditCardHandleId);
        if (empty($creditCardHandleRepository)) {
            return $this->responseJson(11000);//暂不支持该信用卡的申请
        }
        $isCheckUser = $this->isCheckUser($realname, $idCard);
        if (is_object($isCheckUser)) return $isCheckUser;
        $isApply = $this->creditCardHandleApplyRepository->isApply($mobile, $creditCardHandleId);
        if (empty($isApply)) {
            $data = [
                'invited_user_id' => $invitedUserId,
                'apply_realname' => $realname,
                'apply_idcard_number' => $idCard,
                'apply_mobile' => $mobile,
                'bank_code' => $creditCardHandleRepository->bank_code,
                'bank_description' => $creditCardHandleRepository->bank_description,
                'supply_money' => $creditCardHandleRepository->supply_money,
                'profit_money' => $creditCardHandleRepository->profit_money,
                'credit_card_handle_id' => $creditCardHandleRepository->id,
                'review_status' => 7000,
                'identity_type' => $isCheckUser,
                'month_apply_date' => date('Y-m'),
                'apply_date' => date('Y-m-d'),
                'apply_create_time' => time(),
            ];
            $this->creditCardHandleApplyRepository->create($data);
        }
        //提交给第一网申
        $res = $this->submitThreeApiCardHandle($creditCardHandleRepository->handle_url, $realname,
            $mobile, $idCard, $creditCardHandleRepository->channel_no);
        //返回办卡申请url
        $returnHandle = [
            'return_handle_url' => isset($res['data']['creditCardUrl']) ? $res['data']['creditCardUrl'] : ''
        ];
        return $this->responseJson(11001, $returnHandle);
    }

    /**
     * 第一网申办卡接口
     * @param $handleUrl
     * @param $realname
     * @param $mobile
     * @param $idCard
     */
    public function submitThreeApiCardHandle($handleUrl, $realname, $mobile, $idCard, $channelNo)
    {
        $urlInfo = parse_url($handleUrl);
        $urlParams = convertUrlQuery($urlInfo['query']);
        $url = 'http://xykfxsx.hcwjpay.com/merchant/info/registh5';
        $param = [
            'merName' => $realname,
            'merIdentity' => $idCard,
            'merMobile' => $mobile,
            'bankId' => $urlParams['bankId'],
            'creditType' => 0,
            'merAppUuid' => $urlParams['appuuid'],
            'merParentid' => $channelNo,
            'bankCardId' => $urlParams['bankCardId'],
        ];
        $client = new \GuzzleHttp\Client(['verify' => false]);
        $response = $client->request('post', $url, ['json' => $param]);
        $json = json_decode($response->getBody()->getContents(), true);
        return $json;
    }

    /**
     * 卡盟申请办卡接口
     * @param $goodsId
     * @param $realname
     * @param $mobile
     * @param $idCard
     */
//    public function submitThreeApiCardHandle($goodsId, $realname, $mobile, $idCard)
//    {
//        $url = 'http://www.qichangkeji.vip/qckjgzhManager/DownUser/AAAinsertAdd.do';
//        $param = [
//            'ip' => '58.62.164.115',
//            'systemVersion' => 'Mac',
//            'softVersion' => 'Chrome,Chrome,69.0.3497.100',
//            'isChecked' => 1,
//            'goodsId' => $goodsId,
//            'type' => 1,
//            'name' => $realname,
//            'phone' => $mobile,
//            'idCard' => $idCard,
//            'fatherId' => '123655',
//            'otherUserId' => '0',
//        ];
//        $client = new \GuzzleHttp\Client(['verify' => false]);
//        $response = $client->request('post', $url, ['form_params' => $param]);
//        $json = json_decode($response->getBody()->getContents(), true);
//    }

    /**
     * 验证用户
     * @param $realname
     * @param $idCard
     * @return bool|\Illuminate\Http\JsonResponse
     */
    public function isCheckUser($realname, $idCard)
    {
        //先查找用户中是否有该申请人的数据
        $isExistTrueNameUser = $this->userRepository->isExistTrueNameUser($realname, $idCard);
        if (empty($isExistTrueNameUser)) {
            $certificationBankCardMsgAuth = new CertificationBankCardMsgAuth();
            $idcardResult = $certificationBankCardMsgAuth->identityIdCard($idCard, $realname, 'noPhoto', 'A6');
            if ($idcardResult['success'] && 0 == $idcardResult['data']['code']) {
                return 0;
            } else {
                if ($idcardResult['success']) {
                    return $this->responseJson(422, [], false, $idcardResult['data']['desc'], $idcardResult['data']['desc']);
                } else {
                    return $this->responseJson(422, [], false, $idcardResult['errorMsg'], $idcardResult['errorMsg']);
                }
            }
        } else {
            return 1;
        }
    }

    /**
     * 获取办卡分享链接
     * @param $invitedUserId
     * @param $creditCardHandleId
     * @return \Illuminate\Http\JsonResponse
     */
    public function getShareUrl($invitedUserId, $creditCardHandleId)
    {
        //验证需要办理的信用卡是否存在
        $creditCardHandleRepository = $this->creditCardHandleRepository->findByOpen($creditCardHandleId);
        if (empty($creditCardHandleRepository)) {
            return $this->responseJson(11000);//暂不支持该信用卡的申请
        }
        $data = $this->shareParams($invitedUserId, $creditCardHandleId,
            getOssImageUrl($creditCardHandleRepository->card_url), $creditCardHandleRepository->title, $creditCardHandleRepository->keywords);
        return $this->responseJson(0, $data);
    }
}